import 'package:eh_mobile/common/store/store_keys.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class ConfigStore {
  static final ConfigStore _singletonPattern = ConfigStore._internal();

  ///工厂构造函数
  factory ConfigStore() {
    return _singletonPattern;
  }

  ///构造函数私有化，防止被误创建
  ConfigStore._internal();

  // 持久化存储类
  final GetStorage _userStoreCache = GetStorage();
  // APP版本
  String? appVerson;
  // 当前机型
  String? deviceName;
  // 是否是第一次打开
  bool isFirstOpen = false;

  // 国际化配置
  Locale locale = const Locale('en', 'US');
  List<Locale> languages = [
    const Locale('en', 'US'),
    const Locale('zh', 'CN'),
  ];

  // 标记用户已打开过APP
  Future saveAlreadyOpen() async {
    return _userStoreCache.write(STORAGE_DEVICE_FIRST_OPEN_KEY, false);
  }

  void onInitLocale() {
    var langCode = _userStoreCache.read(STORAGE_LANGUAGE_CODE);
    if (langCode.isEmpty) return;
    var index = languages.indexWhere((element) {
      return element.languageCode == langCode;
    });
    if (index < 0) return;
    locale = languages[index];
  }

  void onLocaleUpdate(Locale value) {
    locale = value;
    Get.updateLocale(value);
    _userStoreCache.write(STORAGE_LANGUAGE_CODE, value.languageCode);
  }
}
